<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Service\WeChat;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use App\Http\Models\ZhyReport;


use Config;

class WxController extends Controller
{

    public function index()
    {
        // $imageName = md5(uniqid();
        // echo createQrcode('202306291201#中国光大银行股份有限公司','/images/report/',$imageName);die;
        echo '111';
    }

    public function help()
    {
        return view('web.wx.help');
    }
    
    public function wx_index()
    {
        if (isset($_GET['echostr'])) {
            $this->valid();
        } else {
            $this->responseMsg();
        }
    }


    //首次校验
    public function valid()
    {
        $echoStr = $_GET["echostr"]??'';
        if ($this->checkSignature()) {
            ob_end_clean();
            echo $echoStr;
            exit;
        }
    }

    /*
    * 校验url与token的合法性，激活开发者默模式
    */
    public function checkSignature()
    {
        $signature = $_GET["signature"]??'';
        $timestamp = $_GET["timestamp"]??'';
        $nonce = $_GET["nonce"]??'';
        $token = Config::get('wechat.TOKEN');
        $tmpArr = [
            $token,
            $timestamp,
            $nonce,
        ];
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /*
    * 响应事件
    */
    public function responseMsg()
    {
        $postStr = file_get_contents("php://input");

        // $postStr = "<xml><ToUserName><![CDATA[gh_7320827cb230]]></ToUserName><FromUserName><![CDATA[oiXRZ6ym25HCpgy_DsMzGVKdGzQA]]></FromUserName><CreateTime>1688373639</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[scancode_waitmsg]]></Event><EventKey><![CDATA[scancode_waitmsg_0]]></EventKey><ScanCodeInfo><ScanType><![CDATA[qrcode]]></ScanType><ScanResult><![CDATA[http://test.zhonghengye.cn//wx-help?s=eyJpdiI6IitWT21iRTR5YWlhZGpVVTBzV2RiUUE9PSIsInZhbHVlIjoidEx2WFwvdWFZano3NXdXdWRPRmlHWXc9PSIsIm1hYyI6ImQ3YzZmZGM1Y2EyNGI0MmEwZTE4NmYwMWZkYjllOTdlMDRlODNmOThmNWQxMjkyZDZjMzQwYzdkZWYxM2Y1NmIifQ==]]></ScanResult></ScanCodeInfo></xml>";

        // $postStr = '<xml><ToUserName><![CDATA[gh_7320827cb230]]></ToUserName><FromUserName><![CDATA[oiXRZ6ym25HCpgy_DsMzGVKdGzQA]]></FromUserName><CreateTime>1688022302</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[202306291201#中国光大银行股份有限公司]]></Content><MsgId>24166668757985898</MsgId></xml>';

        // $insertArr = [
        //     'company_name'    => $postStr,
        //     'number'          => '222',
        //     'position'        => '1',
        //     'client'          => '1',
        //     'total_price'     => '1',
        //     'price'           => '1',
        //     'built_in'        => '1',
        //     'property_nature' => '1',
        //     'is_change'       => '1',
        //     'created_at'      => date('Y-m-d H:i:s',time()),
        //     'updated_at'      => date('Y-m-d H:i:s',time()),
        // ];
        
        // ZhyReport::insert($insertArr);

        
        if(empty($postStr)) exit('error');

        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        // print_r($postObj);die;
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $keyword = $postObj->Content;
        $type = trim($postObj->MsgType);//获取用户发来的消息类型（可能是文字，也可能是事件推送）
        $customevent = trim($postObj->Event);//获取用户是关注还是点击

        //根据事件类型得到回复内容
        switch ($type) {
            case 'event':
                
                switch ($customevent) {
                    //当消息类型为事件推送，并且customevent 为 subscribe（关注）的情况时
                    case 'subscribe':
                        $contentStr = "你好，欢迎关注中恒业评估！";
                        WeChat::resonseText($fromUsername, $toUsername, $contentStr);
                        break;
                    case 'unsubscribe':
                        
                        break;
                    case 'CLICK':
                        $eventKey = trim($postObj->EventKey);//菜单的自定义的key值，可以根据此值判断用
                        if($eventKey == 'click_0'){//手输验证
                            // $contentStr = "请输入你需输入的报告编号+委托方名称，以空格键或#隔开；如1234567 张三 或1234567#张三\n注意：存在多个委托方名称只需输入任意一个";
                            $contentStr = "请输入你要查询的报告编号，如：202306010001";
                            WeChat::resonseText($fromUsername, $toUsername, $contentStr);
                        }
                        
                        break;
                    case 'VIEW'://连接跳转事件

                        break;
                    case 'scancode_waitmsg':
                        $eventKey = trim($postObj->EventKey);//菜单的自定义的key值，可以根据此值判断用
                        if($eventKey == 'scancode_waitmsg_0'){
                            $scanResult = parse_url($postObj->ScanCodeInfo->ScanResult);
                            if(isset($scanResult['query'])){
                                parse_str($scanResult['query'],$arr);
                                $keyword = decrypt($arr['s']);
                            }else{
                                $keyword = '报告不存在，请扫描正确的二维码！';
                            }
                            $contentStr = $this->getReportContentStr($keyword,2);
                            WeChat::resonseText($fromUsername, $toUsername, $contentStr);
                        }

                        break;
                }
                break;
            //send text message
            case 'text':
                
                $contentStr = $this->getReportContentStr($keyword);
                WeChat::resonseText($fromUsername, $toUsername, $contentStr);
                break;
            //send image
            case 'image':
                $contentStr = $postObj->MediaId;
                break;
            //send voice
            case 'voice':
                $contentStr = '语音接收成功';
                break;
            //send video
            case 'video':
                $contentStr = '语音接收成功';
                break;
            case 'location':
                $Location_X = $postObj->Latitude;
                $Location_Y = $postObj->Longitude;
                $contentStr = "获取地址成功Location_X:$Location_X,Location_Y:$Location_Y";
                break;
        }

        

    }

    /**
     * type 1手输验证 2扫码验证
     */
    public function getReportContentStr($keyword,$type = 1)
    {
        $arr = explode('#',$keyword);
        $number = $arr[0];
        // $client = $arr[1];
        $report = ZhyReport::where(['number' => $number])->first();
        if($report){
            $str = "中恒业评估查询\n";
            $str .= "报告真伪查询结果\n";
            $str .= "报告编号:".$report->number."\n";
            $str .= "项目位置:".$report->position."\n";
            $str .= "委托方:".$report->client."\n";
            $str .= "总价:".$report->total_price."\n";
            $str .= "单价:".$report->price."\n";
            $str .= "建成年代:".$report->built_in."\n";
            $str .= "产权性质:".$report->property_nature."\n";
            // $str .= "物理结构是否变化:".($report->is_change==1?'有变化':'无变化');
            $contentStr = $str;
        }else{
            if($type == 2){
                $contentStr = "报告不存在，请扫描正确的二维码！";
            }else{
                $contentStr = "报告不存在，请输入正确的报告编号！";
            }
        }
        // if (strpos($keyword, '#') !== false) {
        //     $arr = explode('#',$keyword);
        //     $number = $arr[0];
        //     $client = $arr[1];
        //     $report = ZhyReport::where(['number' => $number])->first();
        //     if($report && in_array($client,explode(',',$report['client']))){
        //         $str = "中恒业评估查询\n";
        //         $str .= "报告真伪查询结果\n";
        //         $str .= "报告编号:".$report->number."\n";
        //         $str .= "项目位置:".$report->position."\n";
        //         $str .= "委托方:".$client."\n";
        //         $str .= "总价:".$report->total_price."\n";
        //         $str .= "单价:".$report->price."\n";
        //         $str .= "建成年代:".$report->built_in."\n";
        //         $str .= "产权性质:".$report->property_nature."\n";
        //         // $str .= "物理结构是否变化:".($report->is_change==1?'有变化':'无变化');
        //         $contentStr = $str;
        //     }else{
        //         if($type == 2){
        //             $contentStr = "报告不存在，请扫描正确的二维码！";
        //         }else{
        //             $contentStr = "报告不存在，请输入正确的报告号与估计委托人信息！";
        //         }
        //     }
        // }else if(strpos($keyword, ' ') !== false){
        //     $arr = explode(' ',$keyword);
        //     $number = $arr[0];
        //     $client = $arr[1];
        //     $report = ZhyReport::where(['number' => $number])->first();
        //     if($report && in_array($client,explode(',',$report['client']))){
        //         $str = "中恒业评估查询\n";
        //         $str .= "报告真伪查询结果\n";
        //         $str .= "报告编号:".$report->number."\n";
        //         $str .= "项目位置:".$report->position."\n";
        //         $str .= "委托方:".$client."\n";
        //         $str .= "总价:".$report->total_price."\n";
        //         $str .= "单价:".$report->price."\n";
        //         $str .= "建成年代:".$report->built_in."\n";
        //         $str .= "产权性质:".$report->property_nature."\n";
        //         // $str .= "物理结构是否变化:".($report->is_change==1?'有变化':'无变化');
        //         $contentStr = $str;
        //     }else{
        //         if($type == 2){
        //             $contentStr = "报告不存在，请扫描正确的二维码！";
        //         }else{
        //             $contentStr = "报告不存在，请输入正确的报告号与估计委托人信息！";
        //         }
        //     }
        // }else{
        //     if($type == 2){
        //         $contentStr = "报告不存在，请扫描正确的二维码！";
        //     }else{
        //         $contentStr = "格式不正确，请按照要求的格式输入！";
        //     }
        // }

        return $contentStr;
    }

  

    

    public function createMenu()
    {
        $res = WeChat::createMenu();
        print_r($res);die;

    }

    

    


}
